package com.tank.game.core.play;

import com.tank.game.api.LaunchPanel;
import com.tank.game.api.LaunchPanelUtils;
import com.tank.game.api.Tank;
import com.tank.game.core.DefaultPosition;
import com.tank.game.core.DefaultRange;
import com.tank.game.core.DefaultTank;

import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * 键盘玩家
 *
 * @author Zed
 */
public class KeyboardPlay extends AbstractPlay {

    public KeyboardPlay(DefaultPlayBuilder builder) {
        super(builder);
    }

    @Override
    protected Tank createTank() {
        DefaultRange range = DefaultRange.newBuilder()
                .position(DefaultPosition.newGamePanelRandomPositionBuilder().build()).build();
        DefaultTank zedTank = DefaultTank.newBuilder()
                .id(this.getId())
                .play(this)
                .range(range)
                .build();
        LaunchPanel launchPanel = LaunchPanelUtils.LAUNCH_PANEL;
        ((JFrame) launchPanel).addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_S) {
                    zedTank.execMove((position, tank) -> {
                        int y = (int) ((position.getY() + 1 * tank.getSpeed()));
                        position.setY(y);
                    });
                }

                if (e.getKeyCode() == KeyEvent.VK_W) {
                    zedTank.execMove((position, tank) -> {
                        int y = (int) ((position.getY() + -1 * tank.getSpeed()));
                        position.setY(y);
                    });
                }

                if (e.getKeyCode() == KeyEvent.VK_A) {
                    zedTank.execMove((position, tank) -> {
                        int x = (int) ((position.getX() + -1 * tank.getSpeed()));
                        position.setX(x);
                    });
                }

                if (e.getKeyCode() == KeyEvent.VK_D) {
                    zedTank.execMove((position, tank) -> {
                        int x = (int) ((position.getX() + 1 * tank.getSpeed()));
                        position.setX(x);
                    });
                }
            }
        });
        return zedTank;
    }

    @Override
    public void close() {

    }
}
